var openId = '';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        value: '',
        desc: '',
        textLength: '',
        images: [],
        fileIDs: [],
        maxCount: 9,
        navIndex: '',
        listInfo: '',
        textWidth: '',
        screenWidth: '',
        avatarUrl: '',
        nickName: ''
    },
    //封装方法（拿取用户信息）
    getOpenid() {
        wx.cloud.callFunction({
            name: 'getOpenid'
        }).then(res => {
            console.log("调用成功", res);
            openId = res.openid
        }).catch(res => {
            console.log("调用失败", res);
        })
    },
    onReady: function () {
        this.getOpenid();
        var that = this
        wx.getSystemInfo({
            success: function (res) {
                // console.log(res);
                that.setData({
                    screenWidth: res.screenWidth,
                });
            }
        });
        // 拿顶部text的宽度
        const query = wx.createSelectorQuery();
        query.select('#text').boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec(function (res) {
            //  console.log(res);
            that.setData({
                textWidth: res[0].width
            })
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options);
        this.setData({
            navIndex: options.index,
            listInfo: options.listInfo
        })
    },
    chooseImage() {
        var that = this
        wx.chooseImage({
            count: that.data.maxCount - that.data.images.length,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                // console.log(res);
                // tempFilePath可以作为img标签的src属性显示图片
                if (that.data.images.length != 0) {
                    that.setData({
                        images: that.data.images.concat(res.tempFilePaths)
                    })
                } else {
                    that.setData({
                        images: res.tempFilePaths
                    })
                }
            }
        })
    },
    previewImage(e) {
        var that = this
        wx.previewImage({
            current: that.data.images[e.currentTarget.dataset.index], // 当前显示图片的http链接
            urls: that.data.images // 需要预览的图片http链接列表
        })
    },
    DeleteImg(e) {
        var that = this
        // console.log(11);
        wx.showModal({
            title: '确定删除吗？',
            content: '',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    that.data.images.splice(e.currentTarget.dataset.index, 1);
                    that.setData({
                        images: that.data.images
                    })
                }
            }
        })
    },
    bindInput(e) {
        // console.log(e);
        var that = this;
        that.setData({
            desc: e.detail.value,
            textLength: e.detail.cursor
        })
    },
    publish() {
        var that = this
        let desc = this.data.desc
        let images = this.data.images
        if (!desc || !images) {
            wx.showToast({
                icon: "none",
                title: '请输入内容或选择图片'
            })
            return
        }
        wx.showLoading({
            title: '发布中...',
        })
        const get = wx.cloud.database()
        get.collection('userInfo').where({
            _openid: 'openId' // 填入当前用户 openid
        }).get()
        .then(res => {
            console.log("拿取数据成功",res);
            this.setData({
                avatarUrl: res.data[0].avatarUrl,
                nickName: res.data[0].nickName
            })
        })
        .catch(res => {
            console.log("拿取数据失败",res);
           
        })
        const promiseArr = []
        //遍历临时数组上传
        for (let i = 0; i < this.data.images.length; i++) {
            let filePath = this.data.images[i]
            let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式，获取文件扩展名
            //在每次上传的时候，就往promiseArr里存一个promise，只有当所有的都返回结果时，才可以继续往下执行
            promiseArr.push(new Promise((reslove, reject) => {
                wx.cloud.uploadFile({
                    cloudPath: 'userImage/' + new Date().getTime() + suffix,
                    filePath: filePath, // 文件路径
                }).then(res => {
                    // get resource ID
                    console.log("上传结果", res.fileID)
                    this.setData({
                        fileIDs: that.data.fileIDs.concat(res.fileID)
                    })
                    reslove()
                }).catch(error => {
                    console.log("上传失败", error);
                    wx.hideLoading()
                    wx.showToast({
                        icon: 'none',
                        title: '发布失败'
                    })
                })
            }))
        }
        // 上传到数据库uploadInfo集合
        setTimeout(() => {
            Promise.all(promiseArr).then(res => {
                var dbPlus = '';
                const db = wx.cloud.database()
                if (this.data.navIndex == 0) {
                    dbPlus = wx.cloud.database().collection('uploadInfo')
                } else if (this.data.navIndex == 1) {
                    dbPlus = wx.cloud.database().collection('studyCard')
                } else if (this.data.navIndex == 2) {
                    dbPlus = wx.cloud.database().collection('loveWall')
                } else if (this.data.navIndex == 3) {
                    dbPlus = wx.cloud.database().collection('lostThing')
                }
                dbPlus.add({
                    data: {
                        createTime: db.serverDate(),
                        avatarUrl: this.data.avatarUrl,
                        nickName: this.data.nickName,
                        desc: this.data.desc,
                        fileIDs: this.data.fileIDs,
                        images: this.data.images,
                        likeList: [],
                        commentList: []
                    },
                    success: res => {
                        wx.hideLoading()
                        wx.showToast({
                            title: '发布成功',
                        })
                        // console.log('发布成功', res)
                        that.setData({
                            textValue: ''
                        })
                        that.data.images.splice(0, that.data.images.length);
                        that.setData({
                            images: that.data.images
                        })
                    },
                    fail: err => {
                        wx.hideLoading()
                        wx.showToast({
                            icon: 'none',
                            title: '网络不给力....'
                        })
                        console.error('发布失败', err)
                    }
                })
            })
        }, 300);
    },
})